package constants.api;

import play.libs.Crypto;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * 登录授权
 * @author zhangzc@djcars.cn
 * @create 2016/11/29
 */
public class ApiContext implements Serializable {

    public static ThreadLocal<ApiContext> apiContext = new ThreadLocal();

    /**
     * Session ID
     */
    public String sessionId;

    /**
     * 用户ID
     */
    public Long uid;

    /**
     * 设备标识
     */
    public String uuid;

    /**
     * 系统名
     */
    public String os;

    /**
     * 系统版本
     */
    public String osSdk;

    /**
     * 应用版本号
     */
    public Integer vc;

    /**
     * 应用版本名
     */
    public String vn;

    /**
     * 以上数据签名
     */
    public String sign;

    /**
     * wx用户openId
     */
    public String openId;

    public String sessionKey;

    public void signThis(){
        StringBuilder sb = new StringBuilder();
        List<String> contents = Arrays.asList(
                sessionId, String.valueOf(uid), uuid, os, osSdk, String.valueOf(vc), vn
        );

        contents.forEach((c)-> sb.append(c));

        this.sign = Crypto.sign(sb.toString());
    }

    public static boolean checkSign(String sign, String sessionId, Long uid, String uuid, String os, String osSdk, Integer vc, String vn){
        StringBuilder sb = new StringBuilder();
        List<String> contents = Arrays.asList(
                sessionId, String.valueOf(uid), uuid, os, osSdk, String.valueOf(vc), vn
        );

        contents.forEach((c)-> sb.append(c));

        String _sign = Crypto.sign(sb.toString());
        return StringUtils.equals(_sign, sign);
    }
}
